<?php
$mysqli = new mysqli('localhost', 'db_user', 'db_password', 'db_name');

if ($mysqli->connect_error) {
    die("数据库连接失败: " . $mysqli->connect_error);
}

$username = $mysqli->real_escape_string($_POST['username']);
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$email = $mysqli->real_escape_string($_POST['email']);

// 检查是否存在未激活的过期用户
$check_sql = "SELECT * FROM users WHERE username = '$username'";
$result = $mysqli->query($check_sql);

if ($result->num_rows > 0) {
    $user = $result->fetch_assoc();
    $created_time = strtotime($user['created_at']);
    
    if ($user['is_activated'] == 1) {
        die("用户名已被注册");
    } elseif (time() - $created_time < 3600) {
        die("该用户名正在等待激活，请稍后再试");
    } else {
        $mysqli->query("DELETE FROM users WHERE id = " . $user['id']);
    }
}

// 生成验证码（6位哈希）
$verification_code = substr(md5($username . time()), 0, 6);

// 插入新用户
$insert_sql = "INSERT INTO users (username, password, email, verification_code) 
               VALUES ('$username', '$password', '$email', '$verification_code')";

if ($mysqli->query($insert_sql)) {
    // 发送激活邮件
    $verify_link = "http://127.0.0.1/verify.php?user=" . urlencode($username) . "&code=$verification_code";
    $to = $email;
    $subject = "账户激活邮件";
    $message = "请点击以下链接激活账户（1小时内有效）：\n\n$verify_link";
    $headers = "From: no-reply@example.com";
    
    if (mail($to, $subject, $message, $headers)) {
        echo "注册成功！请检查您的邮箱以激活账户";
    } else {
        echo "邮件发送失败";
    }
} else {
    echo "注册失败: " . $mysqli->error;
}

$mysqli->close();
?>